//
// Created by 32827 on 2024/1/6.
//
#include "user_task.h"
#include "user_ui_main.h"
#include "yzl.h"
uint8_t buffer[128];
YZF_RESULT user_task_i2c_1306_show(){
    if(yzf_area_recv_get_size(yz_recv_transmit_area_get())<1024){
        return YZF_HANDLER_NOT_FINISH;
    }
    for (int i = 0; i < 8; i++) {
        yzl_1306_page_set(I2C0,i);
        yz_time_delay_ms(1);
        yzl_1306_col_low_set(I2C0,2);
        yz_time_delay_ms(1);
        yzl_1306_col_high_set(I2C0,0);
        yz_time_delay_ms(1);
        YZF_RECV_DATA_INDEX most_size=yz_recv_transmit_once_line_most();
        if(most_size>=128){
            yzl_1306_datas_write(I2C0, yzf_area_recv_get_read_ptr(yz_recv_transmit_area_get()),128);
            yzf_area_recv_del(yz_recv_transmit_area_get(),128);
        }
        if(most_size<128){
            yzl_1306_datas_write(I2C0, yzf_area_recv_get_read_ptr(yz_recv_transmit_area_get()),most_size);
            yzf_area_recv_del(yz_recv_transmit_area_get(),most_size);
            yz_time_delay_ms(1);
            most_size=128-most_size;
            yzl_1306_datas_write(I2C0, yzf_area_recv_get_read_ptr(yz_recv_transmit_area_get()),most_size);
            yzf_area_recv_del(yz_recv_transmit_area_get(),most_size);
        }
        yz_time_delay_ms(1);
    }
    yz_ok("1306 信息发送成功\n");
    yz_recv_transmit_reset();
    return YZF_OK;
}
YZF_RESULT user_task_i2c_1306_init(){
    YGPIO(GPIOB)
    YPIN(GPIO_PIN_6)
    yzf_gpio_open_clock_();
    yzf_gpio_set_AFOD_();
    yzf_gpio_set_HIGH_();
    YPIN(GPIO_PIN_7)
    yzf_gpio_set_AFOD_();
    yzf_gpio_set_HIGH_();

    gpio_af_set(GPIOB,GPIO_AF_4,GPIO_PIN_6);//端口复用为串口模式
    gpio_af_set(GPIOB,GPIO_AF_4,GPIO_PIN_7);

    yz_i2c_add7_high_open(I2C0,0x78,400000);

    yzl_1306_close(I2C0);

    yzl_1306_open(I2C0);
    yz_time_delay_ms(1);
    yzl_1306_light_screen(I2C0);
    yz_time_delay_ms(1);
    yzl_1306_light_level_screen(I2C0,128);
    yz_time_delay_ms(1);
    yzl_1306_ram_inc_set(I2C0,YZL_1306_RAM_INC_MODE_PAGE);
    yz_time_delay_ms(1);
    yzl_1306_direction_set(I2C0,YZL_1306_DIRECTION_LEFT_TO_RIGHT);
    yz_time_delay_ms(1);
    yzl_1306_direction_set(I2C0,YZL_1306_DIRECTION_BOTTOM_TO_TOP);
    yz_time_delay_ms(1);
    yzl_1306_content_screen(I2C0);
    yz_time_delay_ms(1);
    yzl_1306_clock_set(I2C0,YZL_1306_LED_CLOCK_MAX);

    yz_info("1306 开启成功\n");

    yz_recv_transmit_reset();
    return YZF_OK;
}

YZF_RESULT user_task_i2c_1306_test(){
    memset(buffer,0b011000000,128);
    for (int i = 0; i < 8; i++) {
        yzl_1306_page_set(I2C0,i);
        yzl_1306_col_low_set(I2C0,2);
        yzl_1306_col_high_set(I2C0,0);
        yzl_1306_datas_write(I2C0, buffer,128);
    }
    yz_recv_transmit_reset();
    return YZF_OK;
}
FIL fnew;
DIR fdir;
YZF_RESULT user_task_SDIO_SDCARD_TEST(){
    FRESULT res_sd;                /* 文件操作结果 */
    UINT fnum;                        /* 文件成功读写数量 */
    BYTE ReadBuffer[1024]= {0};       /* 读缓冲区 */
    BYTE WriteBuffer[] =              /* 写缓冲区*/
            "12345\r\n";

    /*--------------------- 文件系统测试：写测试 -----------------------*/
    /* 打开文件，如果文件不存在则创建它 */
    yz_info("\r\n****** 即将进行文件写入测试... ******\r\n");
    res_sd=f_open(&fnew,"/MMC/FatFs读写测试文件.txt",FA_CREATE_ALWAYS|FA_WRITE);
    if ( res_sd == FR_OK ) {
        yz_info("》打开/创建FatFs读写测试文件.txt文件成功，向文件写入数据。\r\n");
        /* 将指定存储区内容写入到文件内 */
        res_sd=f_write(&fnew,WriteBuffer,sizeof(WriteBuffer),&fnum);
        if (res_sd==FR_OK) {
            yz_info("》文件写入成功，写入字节数据：%d\n",fnum);
            yz_info("》向文件写入的数据为：\r\n%s\r\n",WriteBuffer);
        } else {
            yz_info("！！文件写入失败：(%d)\n",res_sd);
        }
        /* 不再读写，关闭文件 */
        f_close(&fnew);
    } else {
        yz_info("！！打开/创建文件失败。\r\n");
    }

    /*------------------ 文件系统测试：读测试 --------------------------*/
    yz_info("****** 即将进行文件读取测试... ******\r\n");
    res_sd=f_open(&fnew,"/MMC/FatFs读写测试文件.txt",FA_OPEN_EXISTING|FA_READ);
    if (res_sd == FR_OK) {
        yz_info("》打开文件成功。\r\n");
        res_sd = f_read(&fnew, ReadBuffer, sizeof(ReadBuffer), &fnum);
        if (res_sd==FR_OK) {
            yz_info("》文件读取成功,读到字节数据：%d\r\n",fnum);
            yz_info("》读取得的文件数据为：\r\n%s \r\n", ReadBuffer);
        } else {
            yz_info("！！文件读取失败：(%d)\n",res_sd);
        }
    } else {
        yz_info("！！打开文件失败。\r\n");
    }
    /* 不再读写，关闭文件 */
    f_close(&fnew);

    yz_recv_transmit_reset();
    return YZF_OK;
}
YZF_RESULT user_task_screen_test(){
    uint16_t *ptr=(void*)YZL_TLI4384_RAM_ADD;
    for(int i=0;i<800*40;i++){
        ptr[i]=CYAN.data;
        ptr[800*40+i]=RED.data;
    }
    yz_recv_transmit_reset();
    return YZF_OK;
}
uint8_t DialogCount=0;
void yzl_ui_dialog_listener(void *widget,YZL_UI_CTR_EVENT event){
    if(event==YZL_UI_CTR_EVENT_TOUCH_UP){
        YZL_WIDGET *widget1=widget;
        yzlActiveData.handleView=(void*)widget1->parent;
        yzlActiveData.Event=YZL_UI_CTR_EVENT_VIEW_REMOVE_CHILD;
        yzlActiveData.Data=widget1;
        ((YZL_VIEW *)widget1->parent)->act(&yzlActiveData);
        DialogCount--;
    }
}
YZF_RESULT user_task_dialog_test(){
    YZL_VIEW *pView=&YZL_TopView(YZL_UI_Root);
    yzl_ui_dialog_create(&pView->pWidget[pView->WidgetCount],600,20,0,120,32,WHITE,RED,"你好,测试");
    yzl_ui_dialog_set_listener(&pView->pWidget[pView->WidgetCount], yzl_ui_dialog_listener);
    yzlActiveData.handleView=pView;
    yzlActiveData.Event=YZL_UI_CTR_EVENT_VIEW_ADD_CHILD;
    yzlActiveData.Data=YZF_NULL_PTR;
    pView->act(&yzlActiveData);
    yz_recv_transmit_reset();
    return YZF_OK;
}

void addDialog(utf8* text){
    YZL_VIEW *pView=&YZL_TopView(YZL_UI_Root);
    YZL_WIDGET * pRam=&YZL_TopView(YZL_UI_Root).pWidget[YZL_TopView(YZL_UI_Root).WidgetCount];
    yzl_ui_dialog_create(pRam,600,20+DialogCount*30,0,190,24,WHITE,RED,text);
    yzl_ui_dialog_set_listener(pRam, yzl_ui_dialog_listener);
    yzlActiveData.handleView=pView;
    yzlActiveData.Event=YZL_UI_CTR_EVENT_VIEW_ADD_CHILD;
    yzlActiveData.Data=pRam;
    pView->act(&yzlActiveData);
    DialogCount++;
}

YZL_Soft_I2C  l_i2c={YZL_Soft_I2C_MODE_100,GPIO_PIN_5,GPIOC,GPIO_PIN_4,GPIOC};
YZF_RESULT user_task_mpu6050_init(){
    yzl_softport_i2c_init(&l_i2c);

    yzl_mpu6050_soft_init(&l_i2c);
    delay_ms(5);
    YZF_BOOL check=yzl_mpu6050_soft_check(&l_i2c);
    if(check){
        addDialog("Check[OK]");
    }else{
        addDialog("Check[ERROR]");
        yz_recv_transmit_reset();
        return YZF_OK;
    }

    yz_recv_transmit_reset();
    return YZF_OK;
}

YZF_RESULT user_task_ls(){
    while (yzf_area_recv_get_size(yz_recv_transmit_area_get())<sizeof(TASK_LS_REQ_HEADER)){
        vTaskDelay(1);
    };

    //Get Req_header
    YZF_RECV_DATA *req_header= YZL_MEM_MANAGER.pMalloc(sizeof (TASK_LS_REQ_HEADER));
    yzu_area_clone_out(yz_recv_transmit_area_get(),req_header,sizeof (TASK_LS_REQ_HEADER));

    //Get PathStringLen
    while (yzf_area_recv_get_size(yz_recv_transmit_area_get())<((TASK_LS_REQ_HEADER *)req_header)->PathStringLen){
        vTaskDelay(1);
    };
    YZF_RECV_DATA  *path= YZL_MEM_MANAGER.pMalloc(((TASK_LS_REQ_HEADER *)req_header)->PathStringLen+1);
    yzu_area_clone_out(yz_recv_transmit_area_get(),path,((TASK_LS_REQ_HEADER *)req_header)->PathStringLen);
    path[((TASK_LS_REQ_HEADER *)req_header)->PathStringLen]='\0';
    char *path_str=(char *)path;

    //Create Response Header
    TASK_LS_RESP_HEADER *resp_header=(TASK_LS_RESP_HEADER *)YZL_MEM_MANAGER.pMalloc(sizeof (TASK_LS_RESP_HEADER));

    resp_header->status=0;
    resp_header->FileCount=0;
    char **resp_file_name=(char **)YZL_MEM_MANAGER.pMalloc(sizeof (char *)*256);
    uint16_t *resp_file_name_len=(uint16_t *)YZL_MEM_MANAGER.pMalloc(sizeof (uint16_t)*256);

    FRESULT re=f_opendir(&fdir,path_str);
    FILINFO fno;
    if(re!=FR_OK){
        //失败直接返回回应
        resp_header->status=re;
        yz_uart_transmit(TRANSMIT_USART,(uint8_t *)resp_header,sizeof (TASK_LS_RESP_HEADER));
        YZL_MEM_MANAGER.pFree(resp_header);
        YZL_MEM_MANAGER.pFree(path);
        YZL_MEM_MANAGER.pFree(req_header);
        yz_recv_transmit_reset();
        return YZF_OK;
    }else{
        while (YZF_TRUE){
            re = f_readdir(&fdir, &fno);
            if(re !=FR_OK || fno.fname[0] == 0){
                break;
            }
            resp_header->FileCount++;
            resp_file_name[resp_header->FileCount-1]=(char *)YZL_MEM_MANAGER.pMalloc(strlen(fno.fname)+1);
            memcpy(resp_file_name[resp_header->FileCount-1],fno.fname,strlen(fno.fname)+1);
            resp_file_name_len[resp_header->FileCount-1]=strlen(fno.fname);
        }
    }

    //发送回复信息
    yz_uart_transmit(TRANSMIT_USART,(uint8_t *)resp_header,sizeof (TASK_LS_RESP_HEADER));
    yz_uart_transmit(TRANSMIT_USART,(uint8_t *)resp_file_name_len,sizeof (uint16_t)*resp_header->FileCount);
    for(uint16_t i=0;i<resp_header->FileCount;i++){
        yz_uart_transmit(TRANSMIT_USART,(uint8_t *)resp_file_name[i],resp_file_name_len[i]);
        YZL_MEM_MANAGER.pFree(resp_file_name[i]);
    }

    YZL_MEM_MANAGER.pFree(resp_file_name);
    YZL_MEM_MANAGER.pFree(resp_file_name_len);
    YZL_MEM_MANAGER.pFree(resp_header);
    YZL_MEM_MANAGER.pFree(path);
    YZL_MEM_MANAGER.pFree(req_header);
    yz_recv_transmit_reset();
    return YZF_OK;
}

void tf_next_block(uint16_t status){
    TASK_TF_RESP_HEADER resp;
    resp.status=status;
    yz_uart_transmit(TRANSMIT_USART,(uint8_t *)&resp,sizeof (TASK_TF_RESP_HEADER));
}

YZF_RESULT user_task_tf(){
    while (yzf_area_recv_get_size(yz_recv_transmit_area_get())<sizeof(TASK_TF_REQ_HEADER)){
        vTaskDelay(1);
    };
    //Get Req_header
    YZF_RECV_DATA *req_header= YZL_MEM_MANAGER.pMalloc(sizeof (TASK_TF_REQ_HEADER));
    yzu_area_clone_out(yz_recv_transmit_area_get(),req_header,sizeof (TASK_TF_REQ_HEADER));

    //Get PathStringLen
    while (yzf_area_recv_get_size(yz_recv_transmit_area_get())<((TASK_TF_REQ_HEADER *)req_header)->FileSavePathLen){
        vTaskDelay(1);
    };
    YZF_RECV_DATA  *path= YZL_MEM_MANAGER.pMalloc(((TASK_TF_REQ_HEADER *)req_header)->FileSavePathLen+1);
    yzu_area_clone_out(yz_recv_transmit_area_get(),path,((TASK_TF_REQ_HEADER *)req_header)->FileSavePathLen);
    path[((TASK_TF_REQ_HEADER *)req_header)->FileSavePathLen]='\0';
    char *path_str=(char *)path;

    //创建文件
    FRESULT re = f_open(&fnew,path_str,FA_CREATE_ALWAYS | FA_WRITE);
    if(re==FR_OK){
        tf_next_block(0);
        uint32_t recv_count=0;
        uint8_t *buff=YZL_MEM_MANAGER.pMalloc(512);//Block size
        while (recv_count<((TASK_TF_REQ_HEADER *)req_header)->FileSize){
            uint32_t needCount =(((TASK_TF_REQ_HEADER *)req_header)->FileSize-recv_count);
            if(yzf_area_recv_get_size(yz_recv_transmit_area_get())>=512&&needCount>=512){
                yzu_area_clone_out(yz_recv_transmit_area_get(),buff,512);
                UINT wCount=0;
                f_write(&fnew,buff,512,&wCount);
                recv_count+=512;

                tf_next_block(0);

            }else if(needCount<=yzf_area_recv_get_size(yz_recv_transmit_area_get())){
                yzu_area_clone_out(yz_recv_transmit_area_get(),buff,needCount);
                UINT wCount=0;
                f_write(&fnew,buff,needCount,&wCount);
                recv_count+=needCount;

                tf_next_block(0);
            }else{
                vTaskDelay(1);
            }
        }
        f_close(&fnew);
        YZL_MEM_MANAGER.pFree(buff);
    }else{
        tf_next_block(re);
    }
    //释放内存
    YZL_MEM_MANAGER.pFree(req_header);
    YZL_MEM_MANAGER.pFree(path);
    yz_recv_transmit_reset();
    return YZF_OK;
}

YZF_RESULT user_task_rm(){
    while (yzf_area_recv_get_size(yz_recv_transmit_area_get())<sizeof(TASK_RM_REQ_HEADER)){
        vTaskDelay(1);
    };

    yz_recv_transmit_reset();
    return YZF_OK;
}

YZF_RESULT user_task_mkdir(){
    yz_recv_transmit_reset();
    return YZF_OK;
}

//YZF_RESULT user_task_sr04_test(){
////    YZL_GPIO pc4_e={GPIO_PIN_4,GPIOC};
////    YZL_GPIO pc5_t={GPIO_PIN_5,GPIOC};
////    YLGPIO(pc5_t)
////    yzf_gpio_open_clock_();
////    yzf_gpio_set_PP_();
////    yzf_gpio_set_0_();
////    yzf_gpio_set_HIGH_();
////    YLGPIO(pc4_e)
////    yzf_gpio_open_clock_();
////    yzf_gpio_set_IN_FLOAT_();
////    yzf_gpio_set_0_();
////
////    delay_ms(500);
////
////    YLGPIO(pc5_t)
////
////    yzf_gpio_set_1_();
////    delay_us(50);
////    yzf_gpio_set_0_();
////
////
////    while (!(GPIO_ISTAT(GPIOC)&GPIO_PIN_4)){
////        __asm__("nop");
////    }
////    uint32_t t1=*yzl_clock_get()->us;
////    while (GPIO_ISTAT(GPIOC)&GPIO_PIN_4){
////        __asm__("nop");
////    }
////    uint32_t t2=*yzl_clock_get()->us;
////    double  d=(t2-t1)*340/(double)1000000;
////    char *bu= yzu_str_format("distance:%lf\n",d);
////    yzl_iconv_clear_ucs2_buf();
////    utf2ucs(yzl_iconv_ucs2_buf,bu);
////    yzl_ui_draw_rect(400,0,600,16,YZF_TRUE,BLACK);
////    yzl_ui_draw_string(400,0,600,yzl_iconv_ucs2_buf, yzl_iconv_ucs2_strlen(yzl_iconv_ucs2_buf),BLACK,WHITE);
//
//
//
////    YGPIO(GPIOB)
////    YPIN(GPIO_PIN_6)
////    yzf_gpio_open_clock_();
////    yzf_gpio_set_AFOD_();
////    yzf_gpio_set_HIGH_();
////    YPIN(GPIO_PIN_7)
////    yzf_gpio_set_AFOD_();
////    yzf_gpio_set_HIGH_();
////
////    gpio_af_set(GPIOB,GPIO_AF_4,GPIO_PIN_6);//端口复用为串口模式
////    gpio_af_set(GPIOB,GPIO_AF_4,GPIO_PIN_7);
////
////    yz_i2c_add7_high_open(I2C0,0x78,400000);
//
////    yzl_1306_soft_open(&i2c);
////    yzl_clock_delay_s(1);
////    yzl_1306_soft_light_level_screen(&i2c,128);
////    yzl_clock_delay_s(1);
////    yzl_1306_soft_light_level_screen(&i2c,64);
////    yzl_clock_delay_s(1);
////    yzl_1306_soft_light_level_screen(&i2c,32);
////    yzl_clock_delay_s(1);
////    yzl_1306_soft_light_level_screen(&i2c,16);
////    yzl_clock_delay_s(1);
////    yzl_1306_soft_close(&i2c);
//
////    yzl_1306_soft_open(&l_i2c);
////    yzl_clock_delay_s(2);
////    yzl_1306_soft_close(&l_i2c);
////
////
//    int16_t xyz[3];
//    yzl_mpu6050_soft_read_acc(&l_i2c,xyz);
//    double x=xyz[0]/2048.0;
//    double y=xyz[1]/2048.0;
//    double z=xyz[2]/2048.0;
//    char *bu=yzu_str_format("X:%lf\nY:%lf\nZ:%lf",x,y,z);
////    addDialog("TEST");
//
////    delay_ms(5);
////    uint8_t param[2]={0x00,0x10};
////    uint8_t writeData[4]={0x00,0x20,0x40,0x00};
////    YZF_RESULT re=yzl_softport_i2c_param_write(&i2c,0b1010000,param,2,writeData,4);
////    uint8_t da[4];
////    delay_ms(5);
////    re=yzl_softport_i2c_read(&i2c,0b1010000,param,2,da,4);
////    if((*(uint32_t *)da)==(*(uint32_t *)writeData)){
////        addDialog("Check Success");
////    }else{
////        addDialog("Check Error");
////    }
//    yz_recv_transmit_reset();
//    return YZF_OK;
//}